package com.sgb.capital.view.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.CountDownTimer;
import android.view.KeyEvent;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.sgb.capital.R;
import com.sgb.capital.base.BaseActivity;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.databinding.PaydealActivityBinding;
import com.sgb.capital.model.Bean;
import com.sgb.capital.model.BusinessInfoByCompanyEntity;
import com.sgb.capital.model.ListBean;
import com.sgb.capital.model.PayDealBean;
import com.sgb.capital.router.PathCapital;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.view.pop.DataListPop;
import com.sgb.capital.view.pop.NewPayPop;
import com.sgb.capital.view.pop.PayTipPop;
import com.sgb.capital.view.pop.TipPop;
import com.sgb.capital.view.widget.MToast;
import com.sgb.capital.viewmodel.DetailsModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import razerdp.basepopup.BasePopupWindow;

/**
 * 作者:张磊
 * 日期:2021/9/15 0015
 * 说明:支付办理
 */
@Route(path = PathCapital.PayDealActivity)
public class PayDealActivity extends BaseActivity implements NewPayPop.OnPopClickListener {

    private PaydealActivityBinding mBinding;
    private DetailsModel mModel;
    private boolean mIsTimeOut;
    private CountDownTimer mTimer;
    private NewPayPop mPayPop;
    private DataListPop mDataListPop;
    private List<Bean> mBeans;
    private PayDealBean mDealBean;
    private int mIndex;
    Map<String, Object> mBalancemap = new HashMap<>();
    private BusinessInfoByCompanyEntity mUserInfo;
    private String mType = "-1";
    private TipPop mTip;
    private PayTipPop mPayTipPop;
    private boolean isError;
    private boolean isErrorMoney;
    private String mReviewerUserNo = "";
    private String mReviewerPhone;
    private List<ListBean> mListBeans;
    private boolean mIsPay;
    private String mMoney = "";


    /**
     * @param context 上下文
     * @param orderId 订单id
     * @param isPay   是否是支付
     * @param money   转账金额
     */

    public static void start(Context context, String orderId, boolean isPay, String money) {
        Intent intent = new Intent(context, PayDealActivity.class);
        intent.putExtra("orderId", orderId);
        intent.putExtra("isPay", isPay);
        intent.putExtra("money", money);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    /**
     * @param context 上下文
     * @param orderId 订单id
     */

    public static void start(Context context, String orderId) {
        Intent intent = new Intent(context, PayDealActivity.class);
        intent.putExtra("orderId", orderId);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }


    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        mIsPay = getIntent().getBooleanExtra("isPay", true);
        mMoney = getIntent().getStringExtra("money");
        mBinding = DataBindingUtil.setContentView(this, R.layout.paydeal_activity);
        mModel = new ViewModelProvider(this).get(DetailsModel.class);
        mPayPop = new NewPayPop(this, this);
        mTip = new TipPop(this, "温馨提示", "银行卡信息错误，请重新核对信息", null, "知道了");
        mBinding.tvTime.setVisibility(mIsPay ? View.INVISIBLE : View.GONE);
        mPayTipPop = new PayTipPop(mContext);
        mPayPop.mTvTitle.setText("付款验证码");
        mPayPop.mPayButton.setText("立即付款");
        mPayPop.mBackOrder.setText(mIsPay ? "返回订单" : "立即查看");
        mPayPop.mTvTip.setText(mIsPay ? "付款成功" : "转账成功");
        mPayPop.mTvOk.setText(mIsPay ? "付款成功" : "支付成功");
        mPayPop.mTvShowTip.setVisibility(mIsPay ? View.INVISIBLE : View.VISIBLE);
        mBinding.tvTitle.setText(mIsPay ? "支付办理" : "转账汇款");
        mDataListPop = new DataListPop(this);
    }

    public void initData() {
        mModel.getBusinessInfoByUser(this);
        mModel.list(this);
    }

    public void initListener() {
        mPayTipPop.tvCall.setOnClickListener(v -> callPhone());
        mPayTipPop.mTvSure.setOnClickListener(v -> {
            Utils.sendMsg(Constants.EVENT_HIDE_ORDERID, false);
            mPayTipPop.dismiss();
            finish();
        });
        mBinding.ivBack.setOnClickListener(v -> {
            mTip.initStr("您要放弃此次支付吗？", "继续支付", "放弃");
            mTip.show();
        });
        mBinding.llBtn.setOnClickListener(v -> mDataListPop.show());
        mTip.mTvCancel.setOnClickListener(v -> {
            mTip.dismiss();
            if (mTip.mTip.contains("余额不足")) {
                mModel.payInfo(this, mDealBean.orderId, "2");
                return;
            }
            if (mTip.mTvCancel.getText().toString().contains("放弃") && !mTip.mTip.contains("相同")) {
                Utils.sendMsg(Constants.EVENT_HIDE_ORDERID, false);
                finish();
                return;
            }

            if (Utils.isEmpty(mType)) {
                return;
            }
            if (mType.equals("E00000003")) {
                mModel.payInfo(this, mDealBean.orderId, "2");
                return;
            }
            if (mType.contains("E000003")) {
                return;
            }
            if (mIsTimeOut && mIsPay) {
                mModel.payInfo(this, mDealBean.orderId, "2");
            }
            if (mType.equals("E0000011") || mType.equals("E0000012")) {
                mModel.list(this);
                return;
            }
            if (isError) {
                startActivity(new Intent(this, OrderErrorActivity.class));
                return;
            }
        });
        mTip.mTvSure.setOnClickListener(v -> {
            mTip.dismiss();
            if (mTip.mTvSure.getText().toString().contains("继续") && mTip.mTip.contains("相同")) {
                String mobileId = mReviewerPhone;
                mPayPop.mPhoneNumber.setText("请输入手机验证码(" + mobileId.substring(0, 3) + "****" + mobileId.substring(mobileId.length() - 4) + ")");
                mPayPop.mClickListener.onClickNewGet();
            }
        });
        mPayTipPop.tvCall.setOnClickListener(v -> {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + "400-001-0051");
                    intent.setData(data);
                    startActivity(intent);
                }
        );
        mBinding.tvBtnPay.setOnClickListener(v -> {
            if (Utils.isEmpty(mBinding.tvNamePhone.getText().toString())) {
                mType = "E0000012";
                mTip.initStr("复核人员为空，请在电脑端-业务管理-复核配置进行相关人员的配置！", null, "知道了");
                mTip.show();
                return;
            }
            if (mIsTimeOut && mIsPay) {
                mTip.initStr("支付超时，请重新发起支付", null, "知道了");
                mTip.show();
                return;
            }
            mModel.payValidation(PayDealActivity.this, mDealBean.tradeNo, mReviewerUserNo);
        });

        mDataListPop.setOnDismissListener(new BasePopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (mDataListPop.mDataBean == null) return;
                mBinding.tvNamePhone.setText(mDataListPop.mDataBean.no);
                mReviewerUserNo = mDataListPop.mDataBean.name;
                mReviewerPhone = mDataListPop.mDataBean.phone;
            }
        });
        mPayPop.mBackOrder.setOnClickListener(v -> {
            mPayPop.dismiss();
            finish();
            Utils.sendMsg(Constants.EVENT_HIDE_ORDERID, true);
        });
    }

    @Override
    public void initObserve() {
        mModel.mUserBusinessInfoByCompanyEntity.observe(this, businessInfoByCompanyEntity -> {
            mUserInfo = businessInfoByCompanyEntity;
            mModel.payInfo(this, getIntent().getStringExtra("orderId"), "2");
        });
        mModel.mState.observe(this, s -> {
            mType = s;
            if (Utils.isEmpty(s)) {
                String mobileId = mReviewerPhone;
                mPayPop.mPhoneNumber.setText("请输入手机验证码(" + mobileId.substring(0, 3) + "****" + mobileId.substring(mobileId.length() - 4) + ")");
                mPayPop.mClickListener.onClickNewGet();
                return;
            }
            if ("E000001".equals(s)) {
                mTip.initStr("订单异常，无法付款，可前往业务管理-异常订单查看详情！", null, "知道了");
                mTip.show();
                isError = true;
            } else if ("E000007".equals(s)) {
                mPayTipPop.show();
                mPayPop.dismiss();
            } else if ("E000003".equals(s)) {
                isErrorMoney = true;
                mTip.initStr("您已向当前商户支付过一笔相同金额的订单，请确认是否继续支付！", "继续支付", "放弃");
                mTip.show();
            } else if ("E000009".equals(s)) {
                mTip.initStr("订单异常，无法付款，可前往业务管理-异常订单查看详情！", null, "知道了");
                mTip.show();
                isError = true;
            } else if ("E0000012".equals(s)) {
                mTip.initStr("复核人员为空，请在电脑端-业务管理-复核配置进行相关人员的配置！", null, "知道了");
                mTip.show();
                return;
            } else if ("E0000011".equals(s)) {
                mTip.initStr("复核人员状态已变更，请重新选择！", null, "知道了");
                mTip.show();
            } else if ("E0000013".equals(s) && mIsPay) {
                mTip.initStr("支付超时，请重新发起支付", null, "知道了");
                mTip.show();
            } else if ("E00000003".equals(s)) {
                mTip.initStr("可用余额不足，请充值余额或更换其他支付方式！", null, "知道了");
                mTip.show();
                mPayPop.dismiss();
            } else {
                mPayTipPop.show();
                mPayPop.dismiss();
            }
        });


        mModel.mListBean.observe(this, listBeans -> {
            mListBeans = listBeans;
            if (listBeans == null || listBeans.size() == 0) {
                mBinding.tvNamePhone.setText("");
                mBinding.llBtn.setEnabled(false);
                return;
            }
            mBinding.llBtn.setEnabled(true);
            mBeans = new ArrayList<>();
            for (ListBean bean : listBeans) {
                String phone = bean.reviewerPhone;
                Bean item = new Bean(bean.reviewerName + " (" + phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4) + ")", bean.reviewerUserNo);
                item.phone = phone;
                mBeans.add(item);
            }
            mBeans.get(0).select = true;
            mReviewerPhone = mListBeans.get(0).reviewerPhone;
            mReviewerUserNo = listBeans.get(0).reviewerUserNo;
            mBinding.tvNamePhone.setText(mBeans.get(0).no);
            mReviewerUserNo = mBeans.get(0).name;
            mDataListPop.mDatas = mBeans;
        });


        mModel.mPayDealBean.observe(this, payDealBean -> {
            mDealBean = payDealBean;
            if (!Utils.isEmpty(mMoney)) {
                mPayPop.mTvShowTip.setText("已成功转账汇款" + mMoney + "，去转账记录中查看吧");
            }
            mBinding.tvOrderAmount.setText("¥" + (mIsPay ? Utils.getDecimalFormat(payDealBean.amount) : mMoney));
            mBinding.tvMoney.setText("¥" + Utils.getDecimalFormat(payDealBean.balance));
            mPayPop.mPayPriceTv.setText("¥" + Utils.getDecimalFormat(payDealBean.amount));
            mBinding.tvMoneyTip.setVisibility(payDealBean.balance - payDealBean.amount >= 0 ? View.GONE : View.VISIBLE);
            mBinding.tvBtnPay.setText("余额支付 " + mBinding.tvOrderAmount.getText().toString());
            mBinding.tvBtnPay.setEnabled(mBinding.tvMoneyTip.getVisibility() == View.VISIBLE ? false : true);
            mBinding.tvBtnPay.setBackground(Utils.getResources().getDrawable(mBinding.tvMoneyTip.getVisibility() == View.VISIBLE ? R.drawable.button2_false : R.drawable.button2));
            // 倒计时
            mIsTimeOut = false;
            mPayPop.mIsTimeOut = false;
            int time = payDealBean.orderLimitTime * 1000;
            mTimer = new CountDownTimer(time, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    long day = millisUntilFinished / (1000 * 60 * 60 * 24);/*单位天*/
                    long hour = (millisUntilFinished - day * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);/*单位时 */
                    long minute = (millisUntilFinished - day * (1000 * 60 * 60 * 24) - hour * (1000 * 60 * 60)) / (1000 * 60);/*单位分以*/
                    AtomicLong second = new AtomicLong((millisUntilFinished - day * (1000 * 60 * 60 * 24) - hour * (1000 * 60 * 60) - minute * (1000 * 60)) / 1000);/*单位秒*/
                    String key = hour + "小时" + minute + "分" + second + "秒";
                    if (second.get() == 1) {
                        Utils.postDelay(() -> second.set(0), 1000);
                    }
                    mBinding.tvTime.setText(Utils.getKeyWordSpan(Utils.getColor(R.color.color_FF6600), "请在" + key + "内完成支付！", key));
                    mBinding.tvTime.setVisibility(View.VISIBLE);
                }

                @Override
                public void onFinish() {
                    mTimer.cancel();
                    mIsTimeOut = true;
                    mPayPop.mIsTimeOut = true;
                }
            };
            if (mIsPay) {
                mTimer.start();
            }
        });
    }

    @Override
    public void onClickNewGet() {
        mBalancemap.put("amount", mDealBean.amount);
        mBalancemap.put("phone", mReviewerPhone);
        mBalancemap.put("tradeNo", mDealBean.tradeNo);
        mBalancemap.put("reviewerNo", mReviewerUserNo);
        mBalancemap.put("payUserName", mUserInfo.custName);
        mModel.balancePayApply(this, mBalancemap);
    }

    @Override
    public void onClickPayButton(String vCode) {
        mBalancemap.put("code", vCode);
        mModel.balancePayConfirm(this, mBalancemap);
    }

    public void set2Confirm() {
        mPayPop.mPayLayout.setVisibility(View.GONE);
        mPayPop.mPaySuccessLayout.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onDestroy() {
        if (mTimer != null) {
            mTimer.cancel();
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void setApplyCount(String s) {
        mPayPop.mPayLayout.setVisibility(View.VISIBLE);
        mPayPop.mPaySuccessLayout.setVisibility(View.GONE);
        mIndex = 0;
        mPayPop.show();
        mPayPop.setStartTimer();
    }


    //显示验证码输入错误的弹框
    public void showErrorCode(String type, String tip) {
        mType = type;
        if ("E000011".equals(type)) {
            mTip.initStr("复核人员状态已变更，请重新选择！", null, "知道了");
            mTip.show();
        } else if ("E000012".equals(type)) {
            mTip.initStr("复核人员为空，请在电脑端-业务管理-复核配置进行相关人员的配置！", null, "知道了");
            mTip.show();
        } else if ("E000013".equals(type)) {
            isErrorMoney = true;
            mTip.initStr("您已向当前商户支付过一笔相同金额的订单，请确认是否继续支付！", "继续支付", "放弃");
            mTip.show();
            return;
        } else if ("E000007".equals(type)) {
            mPayTipPop.show();
        } else if ("E000008".equals(type)) {
            mTip.initStr(tip, null, "知道了");
            mTip.show();
        } else if ("E000009".equals(type)) {
            mTip.initStr("订单异常，无法付款，可前往业务管理-异常订单查看详情！", null, "知道了");
            mTip.show();
            isError = true;
        } else if ("E0000010".equals(type)) {
            mTip.initStr(tip, null, "知道了");
            mTip.show();
        } else if ("E00463031".equals(type)) {
            mTip.initStr("银行卡信息错误，请重新核对信息", null, "知道了");
            mTip.show();
        } else if ("E00000003".equals(type)) {
            mTip.initStr("可用余额不足，请充值余额或更换其他支付方式！", null, "知道了");
            mTip.show();
            mPayPop.dismiss();
        } else if ("E00462012".equals(type)) {
            mTip.initStr(tip, null, "知道了");
            mTip.show();
        } else if (type.contains("E00466311")) {
            mIndex++;
            if (mIndex > 3) {
                mTip.initStr("支付失败，请重新支付", null, "知道了");
                mTip.show();
                mPayPop.dismiss();
                return;
            }
            mPayPop.setTipText("验证码错误");
        } else {
            MToast.showToast(Utils.getContext(), tip);
        }
    }


    @Subscribe
    public void getCode(ZMessageEvent event) {
        switch (event.code) {
            case Constants.TIMEOUT:
                mTip.initStr("支付超时，请重新发起支付", null, "知道了");
                mTip.show();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    //显示验证码输入错误的弹框
    public void show2ErrorCode(int type, String tip) {
        if (type == 0) {
            mTip.initStr(tip, null, "知道了");
            mTip.show();
        } else if (type == 1) {
            mTip.initStr("银行卡信息错误，请重新核对信息", null, "知道了");
            mTip.show();
        } else if (type == 2) {
            mIndex++;
            if (mIndex > 3) {
                mTip.initStr("支付失败，请重新支付", null, "知道了");
                mTip.show();
                mPayPop.dismiss();
                return;
            }
            mPayPop.setTipText("验证码错误");
        } else if (type == 3) {
            mTip.initStr(tip.contains("超时") ? "支付失败，请重新支付" : tip.contains("余额") ? "可用余额不足，请充值余额或更换其他支付方式！" : tip, null, "知道了");
            mTip.show();
            mPayPop.dismiss();
        } else if (type == 4) {
            mPayPop.mTip.setText(tip);
        } else if (type == 6) {
            mTip.initStr(tip, null, "知道了");
            mTip.show();
            mPayPop.dismiss();
        } else {
            mPayTipPop.show();
            mPayPop.dismiss();
        }
    }

    public void callPhone() {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + "400-001-0051");
        intent.setData(data);
        startActivity(intent);
    }
}